<template>
  <div class="video-play-ptz-container">
    <div class="header">视频会议</div>
    <div class="video-box">
      <div class="mymeet" id="mymeet"></div>
    </div>
  </div>
</template>

<script setup>
import { getmeeting } from "@/api/videoplan.js";
import { ref, reactive, onBeforeUnmount, onMounted } from "vue";
import { useRoute } from "vue-router";
const route = useRoute();
let opts = ref({});
let chartData = ref("");
const loadScriptAsync = (src) => {
  console.log("loadScriptAsync", src);
  return new Promise((resolve, reject) => {
    let scriptEl = document.createElement("script");
    scriptEl.type = "text/javascript";
    scriptEl.async = true;
    scriptEl.charset = "utf-8";
    scriptEl.src = process.env.NODE_ENV === "development" ? src : "/" + src;
    scriptEl.onload = () => {
      resolve();
    };
    document.body.appendChild(scriptEl);
  });
};
const meetingTitle = ref("");
const state = reactive({
  api: null,
  meet: {},
  people: [],
  dialog: false,
  btngroup: false, //是否主持人
  showv: false,
  visible: false,
  visible2: false,
  cameraUrl: "", //视频地址
  pms: {},
  myPlugin: null,
  curIndex: 0, //视频窗口索引
  islarge: 0, //视频窗口缩放
  meid: "", //jitsi id
});
// 开始会议
const startMeet = async () => {
  let data = {
    // optType: "S",
    // userId: route.query.userId,
    meetingGroupId: "",
    meetingTitle: meetingTitle.value,
    token: route.query.token,
  };
  const res = await getmeeting(data);
  state.meet.meetingId = res.data.meetingId;
};
// 初始化会议
const initMeeting = () => {
  state.meet = "1";
  state.people = "2";
  const domain = "np.bcdtech.cn:8443";
  const options = {
    roomName: meetingTitle.value, //meet name for update
    parentNode: document.querySelector("#mymeet"),
    lang: "zhCN",
    userInfo: {
      displayName: route.query.username, // 当前登录的名字
    },
  };
  console.log("options===============", options);
  state.api = new window.JitsiMeetExternalAPI(domain, options);
  // 当前用户加入会议的事件
  state.api.addListener("videoConferenceJoined", (event) => {
    console.log("这个用户已加入会议", event);
    const { roomName, id, displayName, avatarURL, breakoutRoom } = event;
    state.meid = id;
    state.api.getRoomsInfo().then((res) => {
      let rooms = res.rooms;
      let len = roomName.length;
      let room = rooms.find((x) => x.id.substring(0, len) == roomName);
      if (room) {
        let ps = room.participants;
        let po = ps.find((x) => x.id == id);
        if (po) {
          if (po.role == "moderator") {
            state.btngroup = true;
            //标记开始
            if (state.meet.stateCode == "0") {
              startMeet();
            }
          }
        }
      }
      //检查用户是否非创建者成为主持人
      // if ("" + state.meet.creator != store.user.userInfo.id && state.btngroup) {
      // 	ElMessage.error("主持人尚未进入，请等待...");
      // 	state.btngroup = false; //强制为非主持人，防止退出时关闭会议
      // }
    });
  });

  //收到消息
  state.api.addListener("participantJoined", (peo) => {
    //如果是主持人，检查视频地址和视频时间，发送给进入者
    console.log("peo-----------", peo);
    if (state.btngroup && state.cameraUrl != "") {
      let obj = {
        cameraUrl: state.cameraUrl,
        pms: state.pms,
      };
      state.api.executeCommand(
        "sendEndpointTextMessage",
        peo.id,
        JSON.stringify(obj)
      );
    }
  });

  //收到消息
  state.api.addListener("endpointTextMessageReceived", (ent) => {});

  //当前用户离开
  state.api.addListener("videoConferenceLeft", (ent) => {});
  startMeet();
};
onMounted(async () => {
  console.log("meetIndex mounted------------", route.query);
  meetingTitle.value = route.query.meetingTitle;
  initMeeting();
});
const clostMeet = async () => {
  let data = {
    // optType: "C",
    meetingGroupId: state.meet.meetingId,
  };
  try {
    const response = await getmeeting(data);
    window.close();
  } catch (error) {
    console.error("操作失败:", error);
  }
};
//注销时 销毁组件
onBeforeUnmount(() => {
  if (state.api) {
    state.api.dispose();
    //如果是主持人离开，同时关闭会议
    if (state.btngroup) {
      clostMeet();
    }
  }
});
</script>

<style lang="scss">
.video-play-ptz-container {
  width: 100%;
  height: 100%;
  // overflow: hidden;
  background: #f4f6fa;
  .header {
    width: 100%;
    height: 100rpx;
    background: #fff;
    text-align: center;
    line-height: 100rpx;
  }
  .video-box {
    width: 100%;
    height: 100%;
    .mymeet {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
